/*******************************************************************************
 * copyright (c) 2009 - 2010 Simon Allen
 *
 * This file is part of Convex Media Converter.
 *
 * Convex Media Converter is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * Convex Media Converter is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public
 * License along with Convex Media Converter; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 ******************************************************************************/


#include "MainWindow/mainwindow.h"
#include "preferences.h"
#include "ui_preferences.h"

#include <QFileDialog>


const char *Preferences::SETTING_APPLICATION_ID = "convex";
const char *Preferences::SETTING_SHUTDOWN_WHEN_DONE = "shutdownWhenDone";
const char *Preferences::SETTING_SHOW_NOTIFICATIONS = "showNotifications";
const char *Preferences::SETTING_DEFAULT_OUTPUT_DIR = "defaultOutputDirectory";
const char *Preferences::SETTING_FFMPEG_LOCATION = "ffmpegLocation";
const char *Preferences::SETTING_SAVE_WINDOW_GEOMETRY = "saveWindowGeometry";
const char *Preferences::SETTING_GEOMETRY = "geometry";


/**
  * Initialisation constructor sets up UI.
  * @param newSettings Pointer to program QSettings.
  * @param parent Parent widget.
  */
Preferences::Preferences(PresetSettings *newSettings, QWidget *parent) : QDialog(parent), ui(new Ui::Preferences)
{
	settings = newSettings;

	ui->setupUi(this);

	setWindowIcon(QIcon(CONVEX_LOGO));

	connect(ui->pushButton_outputFolder, SIGNAL(clicked()), this, SLOT(selectOutputDir()));
	connect(ui->pushButton_FFmpegLoc, SIGNAL(clicked()), this, SLOT(selectFFmpegLocation()));
	connect(ui->checkBox_notifications, SIGNAL(toggled(bool)), this, SLOT(setShowNotifications(bool)));
	connect(ui->checkBox_shutdownWhenDone, SIGNAL(toggled(bool)), this, SLOT(setShutdownWhenDone(bool)));
	connect(ui->checkBox_saveWindowGeometry, SIGNAL(toggled(bool)), this, SLOT(setSaveWindowGeometry(bool)));
	connect(ui->pushButton_deletePreset, SIGNAL(clicked()), this, SLOT(deleteSelectedPresets()));

	readSettings();
}

Preferences::~Preferences()
{
	delete ui;

	ui = NULL;
}

/** Read preset info into preferences window. */
void Preferences::readPresets()
{
	QStringList presetNames = settings->childGroups();

	for (QStringList::const_iterator iter = presetNames.begin(); iter != presetNames.end(); iter++)
	{
		QTreeWidgetItem *next = new QTreeWidgetItem(ui->treeWidget_presets);

		if (ui->comboBox_defaultPreset->findText(*iter) == -1)
		{

			ui->comboBox_defaultPreset->addItem(*iter);

			next->setText(0, *iter);

			ui->treeWidget_presets->addTopLevelItem(next);

		}
	}
}

/** Read and store program settings. */
void Preferences::readSettings()
{
	if (!settings->contains(SETTING_DEFAULT_OUTPUT_DIR))
		settings->setValue(SETTING_DEFAULT_OUTPUT_DIR,
				   QVariant::fromValue(QString(getenv("HOME"))));

	ui->label_defaultOutputDir->setText(settings->value(SETTING_DEFAULT_OUTPUT_DIR).toString());

	if (!settings->contains(SETTING_FFMPEG_LOCATION))
		settings->setValue(SETTING_FFMPEG_LOCATION,
				   QVariant::fromValue(QString("/usr/bin/ffmpeg")));

	ui->label_FFmpegLoc->setText(settings->value(SETTING_FFMPEG_LOCATION).toString());

	ui->checkBox_shutdownWhenDone->setChecked(settings->value(SETTING_SHUTDOWN_WHEN_DONE,
						  QVariant::fromValue(false)).toBool());
	ui->checkBox_notifications->setChecked(settings->value(SETTING_SHOW_NOTIFICATIONS,
						   QVariant::fromValue(false)).toBool());
	ui->checkBox_saveWindowGeometry->setChecked(settings->value(SETTING_SAVE_WINDOW_GEOMETRY,
						    QVariant::fromValue(true)).toBool());
}

/** Uses file dialog to select the default output location. */
void Preferences::selectOutputDir()
{
	QString currentOutputDir = settings->value(SETTING_DEFAULT_OUTPUT_DIR).toString();

	if (currentOutputDir.isEmpty())
		currentOutputDir = getenv("HOME");

	QString dir = QFileDialog::getExistingDirectory(this, tr("Select Default Output Folder"),
			currentOutputDir, QFileDialog::ShowDirsOnly);

	ui->label_defaultOutputDir->setText(dir);

	settings->setValue(SETTING_DEFAULT_OUTPUT_DIR, dir);
}

/**
  * Uses file dialog to select FFmpeg binary location.
  * @see getFFmpegLocation()
  */
void Preferences::selectFFmpegLocation()
{
	QString ffmpegLoc = QFileDialog::getOpenFileName(this, "Select FFmpeg binary file", getenv("HOME"));
	MainWindow *window = dynamic_cast<MainWindow *>(parentWidget());

	ui->label_FFmpegLoc->setText(ffmpegLoc);

	settings->setValue(SETTING_FFMPEG_LOCATION, ffmpegLoc);

	int codecStatus = window->setupEncoders(ffmpegLoc);

	if (codecStatus == 1)
		QApplication::quit();

	else if (codecStatus == -1)
		selectFFmpegLocation();
}

/** Deletes selected presets from program. */
void Preferences::deleteSelectedPresets()
{
	int index = -1;
	int defaultPresetIndex = ui->comboBox_defaultPreset->currentIndex();
	QList<QTreeWidgetItem *> list = ui->treeWidget_presets->selectedItems();
	MainWindow *window = dynamic_cast<MainWindow *>(parentWidget());

	for (QList<QTreeWidgetItem *>::const_iterator iter = list.begin();
	iter != list.end(); iter++)
	{
		index = ui->treeWidget_presets->indexOfTopLevelItem(*iter);
		QTreeWidgetItem *tmp = ui->treeWidget_presets->takeTopLevelItem(index);

		ui->comboBox_defaultPreset->removeItem(index);

		if (index < defaultPresetIndex)
			ui->comboBox_defaultPreset->setCurrentIndex(++defaultPresetIndex);

		else if (index == defaultPresetIndex)
			ui->comboBox_defaultPreset->setCurrentIndex(-1);

		window->deletePreset(tmp->text(0));
	}
}
